const { createApp, ref, onMounted, h } = Vue;

const app = createApp({
    setup() {
        const editorMode = ref('text');
        const textValue = ref('');
        const keyName = ref('');
        const tabId = ref(null);
        let jsonEditor = null;

        // 获取 URL 参数
        const getUrlParams = () => {
            const params = new URLSearchParams(window.location.search);
            tabId.value = params.get('tabId');
            keyName.value = params.get('key');
            const value = params.get('value');
            
            if (isJSON(value)) {
                editorMode.value = 'json';
                textValue.value = formatJSON(value);
                if (jsonEditor) {
                    jsonEditor.set(JSON.parse(value));
                }
            } else {
                editorMode.value = 'text';
                textValue.value = value || '';
            }
        };

        // 检查是否为 JSON
        const isJSON = (str) => {
            try {
                JSON.parse(str);
                return true;
            } catch (e) {
                return false;
            }
        };

        // 格式化 JSON
        const formatJSON = (jsonString) => {
            try {
                const obj = JSON.parse(jsonString);
                return JSON.stringify(obj, null, 2);
            } catch (e) {
                return jsonString;
            }
        };

        // 保存值
        const saveValue = async () => {
            let value;
            if (editorMode.value === 'json') {
                try {
                    value = JSON.stringify(jsonEditor.get());
                } catch (e) {
                    alert('Invalid JSON format');
                    return;
                }
            } else {
                value = textValue.value;
                if (editorMode.value === 'json') {
                    try {
                        JSON.parse(value);
                    } catch (e) {
                        alert('Invalid JSON format');
                        return;
                    }
                }
            }

            await chrome.scripting.executeScript({
                target: { tabId: parseInt(tabId.value) },
                args: [keyName.value, value],
                func: (key, value) => {
                    sessionStorage.setItem(key, value);
                }
            });

            window.close();
        };

        // 取消编辑
        const cancel = () => {
            window.close();
        };

        // 初始化
        onMounted(() => {
            // 初始化 JSON 编辑器
            const container = document.querySelector('.json-editor');
            jsonEditor = new JSONEditor(container, {
                mode: 'tree',
                modes: ['tree', 'code'],
                sortObjectKeys: true,
                onChangeText: (jsonString) => {
                    textValue.value = jsonString;
                }
            });

            // 加载数据
            getUrlParams();
        });

        // 渲染函数
        function render() {
            return h('div', { class: 'editor-page' }, [
                // 页面头部
                h('div', { class: 'editor-page-header' }, [
                    h('div', [
                        h('h1', { class: 'page-title' }, 'Edit Value'),
                        h('div', { class: 'key-info' }, [
                            'Key: ',
                            h('span', keyName.value)
                        ])
                    ]),
                    h('div', { class: 'value-type' }, [
                        h('label', [
                            h('input', {
                                type: 'radio',
                                checked: editorMode.value === 'text',
                                onChange: () => editorMode.value = 'text'
                            }),
                            ' Text'
                        ]),
                        h('label', [
                            h('input', {
                                type: 'radio',
                                checked: editorMode.value === 'json',
                                onChange: () => editorMode.value = 'json'
                            }),
                            ' JSON'
                        ])
                    ])
                ]),

                // 编辑器容器
                h('div', { class: 'editor-page-container' }, [
                    h('div', { class: 'json-editor' }),
                    h('textarea', {
                        id: 'valueEditor',
                        style: { display: editorMode.value === 'text' ? 'block' : 'none' },
                        value: textValue.value,
                        onInput: (e) => textValue.value = e.target.value
                    })
                ]),

                // 页面底部
                h('div', { class: 'editor-page-footer' }, [
                    h('button', {
                        class: 'secondary',
                        onClick: cancel
                    }, 'Cancel'),
                    h('button', {
                        onClick: saveValue
                    }, 'Save Changes')
                ])
            ]);
        }

        return {
            render
        };
    },

    render() {
        return this.render();
    }
});

app.mount('#app'); 